# -*- coding: utf-8 -*-

import MySQLdb
import pymongo
from conf import config as conf
import sys
################################################
import time
class TimecostHelper(object):
    def __init__(self):
        self.restart()

    def restart(self):
        self.__start = time.time()

    def get_timecost(self):
        return time.time() - self.__start

    def get_timecost_and_restart(self):
        result = self.get_timecost()
        self.restart()
        return result

################################################
# Consts
FIELDNAME_RECORD_ID = '_record_id'
FIELDNAME_SOURCE = '_src'
FIELDNAME_IN_TIME = '_in_time'
FIELDNAME_UTIME = '_utime'

DATE_STR_FORMAT = '%Y-%m-%d'
DATETIME_STR_FORMAT = DATE_STR_FORMAT + ' %H:%M:%S'

################################################

# MySQLdb非线程安全
def get_mysql_conn():
    mysql_conn = MySQLdb.connect(
        host =      conf.MYSQL['host'],
        port =      conf.MYSQL['port'],
        user =      conf.MYSQL['username'],
        passwd =    conf.MYSQL['password'],
        db =        conf.MYSQL['dbname'],
        charset =   'utf8'
    )
    #mysql_conn.autocommit(True)
    return mysql_conn


#################################################

# pymongo是线程安全的, 并且内建连接池
# http://api.mongodb.com/python/current/faq.html#is-pymongo-thread-safe
try:
    mongo_client = pymongo.MongoClient(
        host = conf.MONGODB['host'],
        port = conf.MONGODB['port']
    )
    mongodbs = {}
except Exception as e:
    print e.message
    sys.exit(0)
for dbname, dbinfo in conf.MONGODB['dbs'].iteritems():
    try:
        db = mongo_client[dbname]
        if dbinfo['username'] != '':
            db.authenticate(dbinfo['username'], dbinfo['password'])
        mongodbs[dbname] = db
    except Exception as e:
        print e.message
        sys.exit(0)
#################################################

def dbrecord_to_dict(descriptions, record):
    return {
        desc[0]: field_value
        for desc, field_value in zip(descriptions, record)
    }

# logging是线程安全的
import logging
#logging.basicConfig(level = logging.DEBUG)
from i_util.logs import LogHandler
log = LogHandler(conf.server['name']+str(conf.server['port']), logging.DEBUG)
